#!/bin/sh

DOCKERLIB=/data/docker
PROJECT_NAME=justinchou/docker-hexo
PROJECT_PATH=${PROJECT_NAME}

NODE=node-v0.12.7.tar.gz
NODEURL="https://nodejs.org/dist/v0.12.7/node-v0.12.7.tar.gz"
REDIS=redis-3.0.2.tar.gz
REDISURL="http://download.redis.io/releases/redis-3.0.2.tar.gz"

install(){
    echo "Installing Docker With Yum..."
    yum install -y docker-io
    echo "Creating Docker Running Path..."
    mkdir ${DOCKERLIB} && chmod 700 ${DOCKERLIB}
}

start(){
    echo "starting docker..."
    # docker -d -g ${DOCKERLIB} &
    service docker start
}

stop(){
    echo "stopping docker..."
    service docker stop
}

build_hexo(){

    flag="0"
    if [ ! -f ${PROJECT_PATH}/${NODE} ]; then
        flag="1"
        wget ${NODEURL} & >> /dev/null 2>&1
    fi
    if [ ! -f ${PROJECT_PATH}/${REDIS} ]; then
        flag="1"
        wget ${REDISURL} & >> /dev/null 2>&1
    fi
    wait

    if [ ! -d ${PROJECT_PATH} ]; then
        mkdir -p ${PROJECT_PATH}
    fi
    if [ ${flag} == "1" ]; then
        mv *.tar.gz ${PROJECT_PATH}
    fi

    docker pull centos
    docker build -t ${PROJECT_NAME} .
    docker images
}

start_hexo(){
    echo "starting ${PROJECT_NAME} ..."
    docker run -d -i -t -p 4000:4000 ${PROJECT_NAME} hexo server --config=/opt/projects/nodejs-hexo/_config.yml --cwd=/opt/projects/nodejs-hexo/
}

case ${1} in

"install")install;;

"start")start;;
"stop")stop;;
"restart")
stop
start
;;

"build_hexo"|"build")build_hexo;;
"start_hexo")start_hexo;;

""|"-h"|"--help")
    echo "Usage ${0} [install|start|stop|restart] OR"
    echo "      ${0} [build_hexo|start_hexo]"
;;

esac
